package com.adinnet.api.product.service.impl;

import com.adinnet.api.product.model.Product;
import com.adinnet.api.product.mapper.ProductMapper;
import com.adinnet.api.product.model.vo.ProductDetailsResp;
import com.adinnet.api.product.model.vo.ProductResp;
import com.adinnet.api.product.service.ProductService;
import com.adinnet.api.productImg.mapper.ProductImgMapper;
import com.adinnet.api.productImg.model.ProductImg;
import com.adinnet.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author zYshuai
 * @since 2020-12-03
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductImgMapper productImgMapper;

    /**
     * 商品列表
     *
     * @param limit
     * @param page
     * @return
     */
    @Override
    public Page<ProductResp> productList(Integer limit, Integer page) {
        return productMapper.productList(new Page<>(page, limit));
    }

    /**
     * 商品详情
     *
     * @param productId
     * @return
     */
    @Override
    public ProductDetailsResp productDetails(Integer productId) {
        ProductDetailsResp resp = new ProductDetailsResp();
        Product product = productMapper.selectById(productId);
        if (null == product) {
            throw new BizException("该商品不存在!");
        }
        BeanUtils.copyProperties(product, resp);
        resp.setProductId(product.getId());
        QueryWrapper<ProductImg> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId).eq("deleted", 0);
        List<ProductImg> productImgs = productImgMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(productImgs)) {
            List<String> images = productImgs.stream().filter(productImg -> StringUtils.isNotEmpty(productImg.getImgUrl())).collect(Collectors.toList()).stream().map(ProductImg::getImgUrl).collect(Collectors.toList());
            resp.setImages(images);
        }else {
            resp.setImages(Lists.newArrayList());
        }
        return resp;
    }
}
